<?php

namespace App\Http\Controllers\App;

use App\Model\SmsMsg;
use App\Model\UserDetail;
use App\Model\UserInterPushInfo;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Controller;

/**
 * Class AuthController
 * @package App\Http\Controllers\App
 */
class AuthController extends Controller
{

    //region 账号加密码登陆
    /**
     * 账号加密码登陆
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function login ( Request $request )
    {
        $rules = [
            'phone' => ['required', 'regex:/^1[345789][0-9]{9}$/'],
            'password' => 'required|string|min:6|max:20'
        ];
        $message = [
            'required' => ':attribute不能为空',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'phone.regex' => '手机号不正确',
        ];
        $attribute = [
            'phone' => '手机号',
            'password' => '密码'
        ];
        $this->validate ( $request, $rules, $message, $attribute );//验证

        $user = User::wherePhone ( $request->input ( "phone" ) )->whereIn ( 'type', [3, 4] )->first ();
        if ($user == null) {
            return $this->fail ( "用户名不存在！" );
        }
        if (!password_verify ( $request->input ( "password" ), $user->password )) {
            return $this->fail ( "用户名或密码错误！" );
        }
        if ($user->is_enabled == 1) {
            return $this->fail ( '你的账号已被禁用' );
        }
        $is_perfect = isset($user->cards) ? true :false;
        //登录成功记录数据
        $this->loginLog ( $user );
        return $this->renderJson ( ['token' => Auth::guard ( 'app' )->fromUser ( $user ), 'expire' => '2592000', 'is_perfect' => $is_perfect] );
    }
    //endregion

    //region 微信登陆
    /**
     * 微信登陆
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function weChatLogin ( Request $request )
    {
        $union_id = $request->input ( "union_id" );
        $user_detail = UserDetail::whereUnionId ( $union_id )->first ();
        if (!$user_detail) {
            return $this->fail ( "需要绑定手机号码！" );
        }
        $user = $user_detail->user;

        if (isset($user->phone) == null) {
            return $this->fail ( "需要绑定手机号码！" );
        }
        $is_perfect = isset($user->cards) ? true :false;
        // 登陆成功
        $this->loginLog ( $user );
        return $this->renderJson ( ['token' => Auth::guard ( 'api' )->fromUser ( $user ), 'expire' => '2592000', 'is_perfect' => $is_perfect] );
    }

    //endregion

    //region 电话登陆
    /**
     * 电话登陆
     * @param Request $request
     * @param User $user
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function phoneLogin ( Request $request, User $user, SmsMsg $msg )
    {
        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
        ] );
        $phone = $request->input ( "phone" );
        $code = $request->input ( "code" );
        // 验证短信
        if ($phone != "15802302783") {
            $msg->validate ( $phone, $code );
        }
        $user = $user->where ( "phone", $phone )->whereIn ( "type", [3, 4] )->first ();
        $is_perfect = isset($user->cards) ? true :false;
        if (!$user) {
            return $this->fail ( "账号不存在！" );
        }
        return $this->renderJson ( ['token' => Auth::guard ( 'api' )->fromUser ( $user ), 'expire' => '2592000', 'is_perfect' => $is_perfect] );
    }

    //endregion

    // region 绑定手机号码
    /**
     * 绑定手机号码
     * @param Request $request
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function bindPhoneLogin ( Request $request, SmsMsg $msg )
    {
        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
        ] );
        $phone = $request->input ( "phone" );
        $code = $request->input ( "code" );
        $union_id = $request->input ( "union_id" );
        // 验证短信
        if ($phone != "15802302783") {
            $msg->validate ( $phone, $code );
        }
        //以前进入过平台的
        if ($user_detail = UserDetail::whereUnionId ($union_id)->first ()) {
            $user = $user_detail->user;
            $user->phone = $phone;
            $user->save ();
            $this->loginLog ( $user );
            $is_perfect = isset($user->cards) ? true :false;
            return $this->renderJson ( ['token' => Auth::guard ( 'api' )->fromUser ( $user ), 'expire' => '2592000', 'is_perfect' => $is_perfect] );
        }
        // 用手机注册过
        if ($user = User::where ( "phone", "=", $phone )->whereIn ( "type", [3, 4] )->first ()) {

            $detail = $user->detail;
            $detail->open_id = $request->input ( "open_id" );
            $detail->union_id = $request->input ( "union_id" );
            $detail->wechat_name = $request->input ( "wechat_name" );
            $detail->head_portrait = $request->input ( "head_portrait" );
            $detail->save ();
            return $this->renderJson ( ['token' => Auth::guard ( 'api' )->fromUser ( $user ), 'expire' => '2592000'] );
        } else {

            // 新用户
            $new_user = new User();
            $new_user->phone = $phone;
            $new_user->save ();
            $detail = new UserDetail();
            $detail->user_id = $new_user->id;
            $detail->open_id = $request->input ( "open_id" );
            $detail->union_id = $request->input ( "union_id" );
            $detail->wechat_name = $request->input ( "wechat_name" );
            $detail->head_portrait = $request->input ( "head_portrait" );
            $detail->save ();
            $this->init ( $new_user );
            $is_perfect = isset($new_user->cards) ? true :false;
            return $this->renderJson ( ['token' => Auth::guard ( 'api' )->fromUser ( $new_user ), 'expire' => '2592000', 'is_perfect' => $is_perfect] );
        }
    }

    //endregion

    //region 注册
    /**
     * 注册
     * @param Request $request
     * @param User $user
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function register ( Request $request, User $user, SmsMsg $msg )
    {

        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
                'unique:users,phone'
            ],
            'password' => 'required|string|min:6|max:20',
            'code' => 'required'
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'phone.unique' => '手机号被注册了',
            'min' => ':attribute不小于:min位',
            'max' => ':attribute不大于:max位',
            'code.required' => '验证码不能为空',
        ] );
        // 验证短信code
        $phone = $request->input ( "phone" );
        $password = bcrypt ( $request->input ( 'password' ) );
        $code = $request->input ( "code" );

//        if ($phone != "15802302783") {
//
            $msg->validate ( $phone, $code );
//        }

        $user->phone = $phone;
        $user->password = $password;
        try{
            DB::beginTransaction ();
            $user->save ();
            $user->detail ()->save ( new UserDetail() ); // 互推信息的添加
            $this->init ( $user );
            DB::commit ();
        }catch (\Exception $exception){
            \Log::error ($exception);
            DB::rollBack();
        }
        $token = Auth::guard ( 'app' )->fromUser ( $user );
        $this->loginLog ( $user );
        DB::table('user_up')->insert([
            'user_id' => $user->id,
            'user_up_list' => 0,
            'created_at' => Carbon::now()
        ]);
        $is_perfect = isset($user->cards) ? true :false;
        return $this->renderJson ( ['token' => $token, 'expire' => '2592000', 'is_perfect' => $is_perfect] );
    }

    //endregion

    //region 修改密码
    /**
     * 修改密码
     * @param Request $request
     * @param SmsMsg $msg
     * @return \Illuminate\Http\Response
     */
    public function retrievePassword ( Request $request, SmsMsg $msg )
    {
        $this->validate ( $request, [
            'phone' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/',
            ],
            'code' => 'required',
            'password' => 'required|string|min:6|max:20'
        ], [
            'phone.required' => '手机号不能为空',
            'phone.regex' => '手机格式错误',
            'code.required' => '验证码不能为空',
            'password.required' => 'password不能为空',
            'password.min' => 'password不小于:min位',
            'password.max' => 'password不大于:max位',
        ] );
        $phone = $request->input ( "phone" );

        $code = $request->input ( "code" );
        $password = bcrypt ( $request->input ( 'password' ) );
        // 验证短信
        $msg->validate ( $phone, $code );
        $user = User::where ( "phone", $phone )->whereIn ( "type", [3, 4] )->first ();
        if (isset( $user )) {
            $user->password = $password;
            $user->save ();
            $token = Auth::guard ( 'app' )->fromUser ( $user );
            return $this->renderJson ( ['token' => $token, 'expire' => '2592000'] );
        }
        return $this->fail ( "账号不存在，请注册！" );
    }

    //endregion

    //region 刚注册初始化用户数据
    /**
     * 刚注册初始化用户数据
     * @param  User $user
     */
    public function init ( $user )
    {
        try{
            \DB::beginTransaction ();
            // 互推信息的增加
            $user_inter_push_info = new UserInterPushInfo();
            $user_inter_push_info->user_id = $user->id;
            $user_inter_push_info->save();
            // 写入互推redis

            $name1 = date('Ymd') . '_0_' . '_city';
            $redis = Redis::connection();
            $redis->select (0);
            $redis->sadd ($name1, $user_inter_push_info->id);
            // 加入次数
            $redis->set("user_id_".$user_inter_push_info->id,2);
            \DB::commit ();
            // 活动佣金
        }catch (\Exception $exception){
            \DB::rollBack ();
            \Log::error ($exception);
        }
    }

    //endregion



    /**
     * 登陆日志
     * @param User $user
     */
    private function loginLog ( User $user )
    {
        $user->logged_ip = request ()->getClientIp ();
        $user->logged_at = date ( 'Y-m-d H:i:s', time () );
        $user->save ();
    }

}
